package com.jumi.microservice.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.InventoryRedisKey;
import com.jumi.microservice.common.constant.ResultEnum;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.common.exception.IResponseExceptionMsg;
import com.jumi.microservice.common.redis.RedisCache;
import com.jumi.microservice.common.utils.ResultGenerator;
import com.jumi.microservice.constant.ExceptionEnum;
import com.jumi.microservice.constant.GoodsTypeEnum;
import com.jumi.microservice.constant.NumberConstant;
import com.jumi.microservice.domain.*;
import com.jumi.microservice.mapper.GoodsStockMapper;
import com.jumi.microservice.mapper.GoodsWarehouseStockMapper;
import com.jumi.microservice.stock.api.IJmStockApi;
import com.jumi.microservice.stock.api.dto.CommodityStockReleaseDTO;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RestController;

import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * - - - - - - - - - - - - - - -
 *
 * @author liuz
 * @date 2020/8/11 16:06
 * ToDoSomeThing
 * - - - - - - - - - - - - - - -
 */
@RestController
@Transactional
@Service
public class GoodsInventoryService implements GoodsInventoryApi {
    private static final Logger logger = LoggerFactory.getLogger(GoodsInventoryService.class);

    @Autowired
    private GoodsStockMapper goodsStockMapper;

    @Autowired
    private GoodsWarehouseStockMapper warehouseStockMapper;

    @Reference
    private IJmStockApi supplySkuStockService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 获取sku的库存信息
     *
     * @param list goodssku对象集合
     * @return
     */
    @Override
    public List<GoodsSkuStockDTO> goodsSkuInventoryList(List<GoodsSkuStockDTO> list) {
        //计算实时库存
        calInventory(list);
        return list;
    }

    /**
     * 保存商品sku库存信息
     *
     * @param supplySkuStockDTO 封装sku库存信息
     * @return
     */
    @Override
    public ResponseResult saveInventory(SupplySkuStockDTO supplySkuStockDTO) {
        //获取库存信息
        List<GoodsSkuStockDTO> stockDTOS = supplySkuStockDTO.getList();
        stockDTOS.stream().forEach(dto -> {
            //判断sku库存是否存在
            GoodsStockDO goodsStock = goodsStockMapper.selectOne(
                    Wrappers.<GoodsStockDO>lambdaQuery()
                            .eq(GoodsStockDO::getGoodsSkuId, dto.getSkuId()));
            if (goodsStock != null) {
                //判断累积的库存是否大于物料库存
                ExceptionEnum.FAIL_STOCK_BIG.doThrowIf((goodsStock.getGoodsSkuStorage() + dto.getStockQuantity()) > dto.getMaterialStorage());
                //更新库存信息
                update(dto, goodsStock);
            } else {
                //添加库存信息
                inser(dto);
            }
        });
//        //调用供应链服务
//        supplySkuStockService.applyForInventory(supplySkuStockDTO.getStockApplyRequest());
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 清除库存
     *
     * @param dto 商品sku库存
     */
    @Override
    public ResponseResult clearInventory(ClearSkuMaterialDTO dto) {
        if (CollectionUtil.isNotEmpty(dto.getSkuIds())) {
            //处理sku总库存
            GoodsStockDO g = new GoodsStockDO();
            //总库存清0
            g.setGoodsSkuStorage(0);
            //锁定库存清0
            g.setLockedStorage(0);
            g.setUpdateTime(LocalDateTime.now());
            goodsStockMapper.update(g,
                    Wrappers.<GoodsStockDO>lambdaUpdate()
                            .in(GoodsStockDO::getGoodsSkuId, dto.getSkuIds()));

            //获取sku的分仓信息
            List<GoodsWarehouseStockDO> warehouseStocks = warehouseStockMapper.selectList(
                    Wrappers.<GoodsWarehouseStockDO>lambdaQuery()
                            .in(GoodsWarehouseStockDO::getGoodsSkuId, dto.getSkuIds()));
            List<GoodsWarehouseStockDO> oldWarehouseStocks = new ArrayList<>(warehouseStocks.size());
            warehouseStocks.stream().forEach(warehouseStock->{
                GoodsWarehouseStockDO goodsWarehouseStockDO = new GoodsWarehouseStockDO();
                goodsWarehouseStockDO.setWarehouseId(warehouseStock.getWarehouseId());
                goodsWarehouseStockDO.setSaleStockQuantity(warehouseStock.getSaleStockQuantity());
                goodsWarehouseStockDO.setGoodsSkuId(warehouseStock.getGoodsSkuId());
                oldWarehouseStocks.add(goodsWarehouseStockDO);
                //库存清0
                warehouseStock.setSaleStockQuantity(0);
                //锁定清0
                warehouseStock.setLockedStockQuantity(0);
                warehouseStock.setUpdateTime(LocalDateTime.now());
                warehouseStockMapper.updateById(warehouseStock);
            });
//            //处理非第三方的分仓的库存
//            GoodsWarehouseStockDO warehouseStock = new GoodsWarehouseStockDO();
//            //库存清0
//            warehouseStock.setSaleStockQuantity(0);
//            //锁定清0
//            warehouseStock.setLockedStockQuantity(0);
//            warehouseStock.setUpdateTime(LocalDateTime.now());
//            int num = warehouseStockMapper.update(warehouseStock,
//                    Wrappers.<GoodsWarehouseStockDO>lambdaUpdate()
//                            .in(GoodsWarehouseStockDO::getGoodsSkuId, dto.getSkuIds()));
            //供应链清除占用
            clearSupplyMaterial(dto, oldWarehouseStocks);
//            //操作完成清除库存
//            if(num>NumberConstant.NUMBER_ZERO.intValue()){
//                clearSupplyStockRedis(dto,warehouseStockes);
//            }
        }
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 通过skuid获取sku的库存
     *
     * @param ids skuid集合
     * @return
     */
    @Override
    public List<GoodsSpuInventoryDTO> goodsInventoryBySkuIds(List<Long> ids) {
        logger.info("通过skuid获取sku的库存");
        //判断id是否空
        if(CollectionUtil.isEmpty(ids)){
            return new ArrayList<>();
        }
        List<GoodsStockDO> stocks = goodsStockMapper.selectList(
                Wrappers.<GoodsStockDO>lambdaQuery()
                        .in(GoodsStockDO::getGoodsSkuId, ids));
        return stocks.stream().map(g -> {
            GoodsSpuInventoryDTO dto = new GoodsSpuInventoryDTO();
            dto.setSpuId(g.getGoodsId());
            dto.setSkuId(g.getGoodsSkuId());
            dto.setStockQuantity(g.getGoodsSkuStorage());
            dto.setSaledStorage(g.getSaledStorage());
            dto.setPreStorage(g.getPreStorage());
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 通过spuid获取库存信息
     * 20210107 修改为按 spuid获取商品的销量
     *
     * @param spuIds 商品spuid
     * @return
     */
    @Override
    public List<GoodsSpuInventoryDTO> goodsInventoryBySpuId(List<Long> spuIds) {
        QueryWrapper<GoodsStockDO> queryWrapper = new QueryWrapper();
        queryWrapper.select("goods_id, sum(saled_storage) saled_storage, sum(goods_sku_storage) goods_sku_storage, sum(pre_storage) pre_storage");
        queryWrapper.in("goods_id", spuIds);
        queryWrapper.groupBy("goods_id");
        List<GoodsStockDO> list = goodsStockMapper.selectList(queryWrapper);
        return list.stream().map(goodsStockDO -> {
            GoodsSpuInventoryDTO goodsSpuInventoryDTO = new GoodsSpuInventoryDTO();
            goodsSpuInventoryDTO.setSpuId(goodsStockDO.getGoodsId());
            goodsSpuInventoryDTO.setSkuId(goodsStockDO.getGoodsSkuId());
            goodsSpuInventoryDTO.setStockQuantity(goodsStockDO.getGoodsSkuStorage());
            goodsSpuInventoryDTO.setSaledStorage(goodsStockDO.getSaledStorage());
            goodsSpuInventoryDTO.setPreStorage(goodsStockDO.getPreStorage());
            return goodsSpuInventoryDTO;
        }).collect(Collectors.toList());
    }

    /**
     * 保存商品sku库存信息(第三方)
     *
     * @param goodsSkuStocks sku库存信息
     * @return
     */
    @Override
    public ResponseResult saveInventory4Third(List<GoodsSkuStockDTO> goodsSkuStocks) {
        goodsSkuStocks.stream().forEach(sku -> {
            logger.info("commodity add third party goods sku stock:{}", sku.toString());
            //判断sku库存是否存在
            GoodsStockDO goodsStock = goodsStockMapper.selectOne(
                    Wrappers.<GoodsStockDO>lambdaQuery()
                            .eq(GoodsStockDO::getGoodsSkuId, sku.getSkuId()));
            if (goodsStock != null) {
                //更新库存信息
                update(sku, goodsStock);
            } else {
                //添加库存信息
                inser(sku);
            }
        });
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 根据spuid获取分仓信息
     *
     * @param goodsSkuStock 商品分仓集合
     * @return
     */
    @Override
    public List<GoodsStockWareDTO> getGoodsStockWare4OrderBySpuId(GoodsSkuStockIdDTO goodsSkuStock) {
        //获取sku的仓库分仓信息
        List<GoodsWarehouseStockDO> goodsWarehouseStockDOS = warehouseStockMapper.selectList(
                Wrappers.<GoodsWarehouseStockDO>lambdaQuery()
                        .in(GoodsWarehouseStockDO::getGoodsSkuId, goodsSkuStock.getSkuIds()));
        //分组仓库信息
        Map<Long, List<GoodsWarehouseStockDO>> wareIds = goodsWarehouseStockDOS.stream().collect(Collectors.groupingBy(GoodsWarehouseStockDO::getWarehouseId));
        List<GoodsStockWareDTO> goodsStockWareDTOS = new ArrayList<>(wareIds.size());
        if (CollectionUtil.isNotEmpty(wareIds)) {
            //商品的sku信息
            List<GoodsSkuStockWareDTO> goodsStockWares = goodsSkuStock.getGoodsStockWares();
            //封装sku分仓信息
            wareIds.forEach((k, v) -> {
                GoodsStockWareDTO goodsStockWareDTO = new GoodsStockWareDTO();
                //过滤出该仓库的所有skuid
                List<Long> ids = v.stream().map(vd -> {
                    return vd.getGoodsSkuId();
                }).collect(Collectors.toList());
                List<GoodsSkuStockWareDTO> dtos = goodsStockWares.stream().filter(g -> ids.contains(g.getSkuId())).collect(Collectors.toList());
                //封装仓库的sku库存
                List<GoodsSkuStockWareDTO> newGoodsWares = goodsSkuAddStock(dtos, v);
                GoodsWarehouseStockDO warehouseStockDO = goodsWarehouseStockDOS.stream().filter(g -> g.getWarehouseId().equals(k)).findAny().orElse(null);
                if (warehouseStockDO != null) {
                    goodsStockWareDTO.setWareId(warehouseStockDO.getWarehouseId());
                    goodsStockWareDTO.setWareName(warehouseStockDO.getWarehouseName());
                    goodsStockWareDTO.setSkuStockWareDTOS(newGoodsWares);
                    goodsStockWareDTOS.add(goodsStockWareDTO);
                }
            });
        }
        return goodsStockWareDTOS;
    }

    /**
     * 订单管理-预售转真实
     *
     * @param wareAndGoodsSkus 仓库-sku信息集合
     * @return
     */
    @Override
    public ResponseResult pre2RealWareStock4Order(WareAndSkuIdsDTO wareAndGoodsSkus) {
        AtomicReference<String> msg = new AtomicReference<>();
        LocalDateTime now = LocalDateTime.now();
        List<GoodsWarehouseStockDO> warehouseStocks = warehouseStockMapper.selectList(
                Wrappers.<GoodsWarehouseStockDO>lambdaQuery()
                        .in(GoodsWarehouseStockDO::getGoodsSkuId, wareAndGoodsSkus.getSkuIds())
                        .in(GoodsWarehouseStockDO::getWarehouseId, wareAndGoodsSkus.getWareIds()));
        if (CollectionUtil.isNotEmpty(warehouseStocks)) {
            //分仓库存更新
            pre2RealWare(warehouseStocks, wareAndGoodsSkus, now, msg);
        }
        //更新sku的总库存信息
        List<GoodsStockDO> goodsStocks = goodsStockMapper.selectList(
                Wrappers.<GoodsStockDO>lambdaQuery()
                        .eq(GoodsStockDO::getGoodsSkuId, wareAndGoodsSkus.getSkuIds()));
        if (CollectionUtil.isNotEmpty(goodsStocks)) {
            Map<Long, Integer> stockMap = wareAndGoodsSkus.getStockMap();
            pre2RealStock(stockMap, goodsStocks, now, msg);
        }
        //当msg不为空时 抛出异常 事务回滚
        if (StringUtils.isNotEmpty(msg.get())) {
            throw new BaseException(new IResponseExceptionMsg(ResultEnum.FAIL.getCode(), msg.get()));
        }
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 根据spuid获取spu的库存
     *
     * @param spuIds
     * @return
     */
    @Override
    public GoodsSpuReturnDTO getGoodsSpuStockBySpuIds(List<Long> spuIds) {
        QueryWrapper<GoodsStockDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("goods_id, sum(goods_sku_storage) goods_sku_storage");
        queryWrapper.in("goods_id", spuIds);
        queryWrapper.groupBy("goods_id");
        List<GoodsStockDO> list = goodsStockMapper.selectList(queryWrapper);
        return new GoodsSpuReturnDTO(list.stream().map(g -> {
            GoodsSpuStockDTO go = new GoodsSpuStockDTO();
            go.setSpuId(g.getGoodsId());
            go.setStockNum(g.getGoodsSkuStorage());
            return go;
        }).collect(Collectors.toList()));
    }

    /**
     * 根据skuid查询sku分仓明细数据
     *
     * @param skuId 商品skuId
     * @return 结果
     */
    @Override
    public List<SkuWarehouseStockDTO> listSkuWarehouseStockDetail(Long skuId) {
        List<SkuWarehouseStockDTO> skuWarehouseStocks = new ArrayList<>();

        List<GoodsWarehouseStockDO> warehouseStocks = warehouseStockMapper.selectList(
                Wrappers.<GoodsWarehouseStockDO>lambdaQuery()
                        .in(GoodsWarehouseStockDO::getGoodsSkuId, skuId));

        if (warehouseStocks != null && warehouseStocks.size() > NumberConstant.NUMBER_ZERO.intValue()) {
            for (GoodsWarehouseStockDO goodsWarehouseStockDO : warehouseStocks) {
                SkuWarehouseStockDTO skuWarehouseStockDTO = new SkuWarehouseStockDTO();
                skuWarehouseStockDTO.setId(goodsWarehouseStockDO.getId());
                skuWarehouseStockDTO.setGoodsSkuId(goodsWarehouseStockDO.getGoodsSkuId());
                skuWarehouseStockDTO.setWarehouseId(goodsWarehouseStockDO.getWarehouseId());
                skuWarehouseStockDTO.setWarehouseName(goodsWarehouseStockDO.getWarehouseName());
                skuWarehouseStockDTO.setSaleStockQuantity(goodsWarehouseStockDO.getSaleStockQuantity());
                skuWarehouseStockDTO.setLockedStockQuantity(goodsWarehouseStockDO.getLockedStockQuantity());
                skuWarehouseStockDTO.setSaledStockQuantity(goodsWarehouseStockDO.getSaledStockQuantity());

                skuWarehouseStocks.add(skuWarehouseStockDTO);
            }
        }
        return skuWarehouseStocks;
    }

    /**
     * 根据spuid集合查询库存
     *
     * @param spuIds 商品spuId集合
     * @return 结果
     */
    @Override
    public Map<Long, Integer> getSaledStorageBySpuIds(List<Long> spuIds) {
        Map<Long, Integer> saledStorageMap = new HashMap<>();

        QueryWrapper<GoodsStockDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("goods_id, sum(saled_storage) saled_storage");
        queryWrapper.in("goods_id", spuIds);
        queryWrapper.groupBy("goods_id");
        List<GoodsStockDO> list = goodsStockMapper.selectList(queryWrapper);
        list.stream().forEach(goodsStockDO -> saledStorageMap.put(goodsStockDO.getGoodsId(), goodsStockDO.getSaledStorage()));
        return saledStorageMap;
    }

    /**
     * 通过spuid获取库存信息
     * 20210107 修改为按 spuid获取商品的销量
     *
     * @param spuIds 商品spuid
     * @return
     */
    @Override
    public List<GoodsSpuInventoryDTO> goodsInventoryBySpuId4Activity(List<Long> spuIds) {
        QueryWrapper<GoodsStockDO> queryWrapper = new QueryWrapper();
        queryWrapper.select("goods_id, sum(saled_storage) saled_storage, sum(goods_sku_storage) goods_sku_storage, sum(pre_storage) pre_storage");
        queryWrapper.in("goods_id", spuIds);
        queryWrapper.groupBy("goods_id");
        List<GoodsStockDO> list = goodsStockMapper.selectList(queryWrapper);
        return list.stream().map(goodsStockDO -> {
            GoodsSpuInventoryDTO goodsSpuInventoryDTO = new GoodsSpuInventoryDTO();
            goodsSpuInventoryDTO.setSpuId(goodsStockDO.getGoodsId());
            goodsSpuInventoryDTO.setSkuId(goodsStockDO.getGoodsSkuId());
            goodsSpuInventoryDTO.setStockQuantity(goodsStockDO.getGoodsSkuStorage());
            goodsSpuInventoryDTO.setSaledStorage(goodsStockDO.getSaledStorage());
            goodsSpuInventoryDTO.setPreStorage(goodsStockDO.getPreStorage());
            return goodsSpuInventoryDTO;
        }).collect(Collectors.toList());
    }


    /**
     * 获取物料的编码
     *
     * @param list
     * @return
     */
    private List<SkuMaterialDTO> getSupplyCodes(List<GoodsSkuStockDTO> list) {
        //获取出skuid及物料编码
        return list.stream().map(dto -> {
            SkuMaterialDTO su = new SkuMaterialDTO();
            su.setMaterialSkuCode(dto.getMaterialSkuCode());
            su.setSkuId(dto.getSkuId());
            return su;
        }).collect(Collectors.toList());
    }

    /**
     * 遍历计算实时库存及物料库存 (不在库存服务调用供应链服务)
     *
     * @param list 商品sku库存信息
     */
    private void calInventory(List<GoodsSkuStockDTO> list) {
//        QueryWrapper<GoodsWarehouseStockDO> queryWrapper = new QueryWrapper<GoodsWarehouseStockDO>();
//        queryWrapper.select("sum(saled_stock_quantity) saledStockQuantity");
        list.stream().forEach(dto -> {
            GoodsStockDO goodsStock = goodsStockMapper.selectOne(
                    Wrappers.<GoodsStockDO>lambdaQuery()
                            .eq(GoodsStockDO::getGoodsSkuId, dto.getSkuId()));
            //实时库存直接取总库存
            if (goodsStock != null && goodsStock.getGoodsSkuStorage() != null) {
                dto.setRealStorage(goodsStock.getGoodsSkuStorage());
            }
            //20210107 添加库存的实时库存修改为 实际+预售
            if(goodsStock != null && goodsStock.getPreStorage() != null){
                dto.setRealStorage(goodsStock.getGoodsSkuStorage()+goodsStock.getPreStorage());
            }
//            //暂时用if处理
//            if (!GoodsTypeEnum.GOODS_TYPE_THREE.equals(dto.getGoodsType())) {
//                //处理自营及组合商品
//                if (goodsStock != null && goodsStock.getGoodsSkuStorage() != null) {
//                    Integer skuStorage = goodsStock.getGoodsSkuStorage();
//                    queryWrapper.eq("goods_sku_id", dto.getSkuId());
//                    //获取仓库的已销售库存
//                    GoodsWarehouseStockDO warehouseStock = warehouseStockMapper.selectOne(queryWrapper);
//                    if (warehouseStock != null && warehouseStock.getSaledStockQuantity() != null) {
//                        dto.setRealStorage(skuStorage - warehouseStock.getSaledStockQuantity());
//                    } else {
//
//                    }
//                }
//                //获取sku的物料库存,预售库存
////                supplys.stream().forEach(su->{
////                    if(dto.getSupplySkuCode().equals(su.getSupplySkuCode())){
////                        dto.setSupplyStorage(su.getSupplyStorage());
////                        dto.setPreStorage(su.getGoodsStorage());
////                    }
////                });
//            } else {
//                //处理第三方商品 实时库存
//                Integer skuStorage = goodsStock.getGoodsSkuStorage();
//                if (skuStorage != null && goodsStock.getSaledStorage() != null) {
//                    dto.setRealStorage(skuStorage - goodsStock.getSaledStorage());
//                }
//            }
        });
    }

    /**
     * 新增库存信息
     *
     * @param dto
     */
    private void inser(GoodsSkuStockDTO dto) {
        GoodsStockDO goodsStock = new GoodsStockDO();
        goodsStock.setUpdateTime(LocalDateTime.now());
        goodsStock.setCreateTime(LocalDateTime.now());
        goodsStock.setGoodsSkuStorage(dto.getStockQuantity());
        goodsStock.setGoodsSkuId(dto.getSkuId());
        goodsStock.setGoodsSkuCode(dto.getSkuCode());
        goodsStock.setGoodsId(dto.getId());
        int insert = goodsStockMapper.insert(goodsStock);

//        if (insert > NumberConstant.NUMBER_ZERO.intValue()) {
//            String skuKey = InventoryRedisKey.GOODS_SKU_STOCK + dto.getSkuId();
//
//            if (!redisCache.hasObjectByKey(skuKey)) {
//                Map<String, Object> dataMap = new HashMap<>();
//                dataMap.put(InventoryRedisKey.GOODSSKUSTORAGE, String.valueOf(goodsStock.getGoodsSkuStorage()));
//                dataMap.put(InventoryRedisKey.LOCKEDSTORAGE, String.valueOf(NumberConstant.NUMBER_ZERO.intValue()));
//                dataMap.put(InventoryRedisKey.SALEDSTORAGE, String.valueOf(NumberConstant.NUMBER_ZERO.intValue()));
//                //dataMap.put(InventoryRedisKey.GOODS_SPU_ID, String.valueOf(goodsStock.getGoodsId()));
//                dataMap.put(InventoryRedisKey.GOODS_TYPE, String.valueOf(dto.getGoodsType()));
//                redisCache.setCacheMap(skuKey, dataMap);
//            }
//        }
    }

    /**
     * 更新库存信息
     *
     * @param dto
     */
    private void update(GoodsSkuStockDTO dto, GoodsStockDO goodsStock) {
        if (dto.getGoodsType().equals(GoodsTypeEnum.GOODS_TYPE_THREE.getCode())) {
            goodsStock.setGoodsSkuStorage(goodsStock.getGoodsSkuStorage() + dto.getStockQuantity());
        } else {
            //暂时用先查再更新 累加库存
            goodsStock.setGoodsSkuStorage(goodsStock.getGoodsSkuStorage() + dto.getStockQuantity());
            goodsStock.setPreStorage(goodsStock.getPreStorage() + dto.getPreStorage());
            goodsStock.setInitialPreStorage(goodsStock.getInitialPreStorage() + dto.getPreStorage());
        }
        goodsStock.setUpdateTime(LocalDateTime.now());
        int update = goodsStockMapper.updateById(goodsStock);

//        if (update > NumberConstant.NUMBER_ZERO.intValue()) {
//            String skuKey = InventoryRedisKey.GOODS_SKU_STOCK + dto.getSkuId();
//
//            if (redisCache.hasObjectByKey(skuKey)) {
//                HashOperations hashOperations = redisTemplate.opsForHash();
//                if (hashOperations.hasKey(skuKey, InventoryRedisKey.GOODSSKUSTORAGE)) {
//                    hashOperations.increment(skuKey, InventoryRedisKey.GOODSSKUSTORAGE, dto.getStockQuantity());
//                }
//            }
//        }
    }

    /**
     * 封装sku的库存信息
     *
     * @param dtos
     * @param warehouseStocks
     */
    private List<GoodsSkuStockWareDTO> goodsSkuAddStock(List<GoodsSkuStockWareDTO> dtos, List<GoodsWarehouseStockDO> warehouseStocks) {
        List<GoodsSkuStockWareDTO> goodsSkuStockWareDTOS = new ArrayList<>();
        warehouseStocks.stream().forEach(dto -> {
            GoodsSkuStockWareDTO goodsSkuStockWareDTO = dtos.stream().filter(p -> p.getSkuId().equals(dto.getGoodsSkuId())).findAny().orElse(null);
            GoodsSkuStockWareDTO newGoodsSkuStockWareDTO = new GoodsSkuStockWareDTO();
            newGoodsSkuStockWareDTO.setSkuId(goodsSkuStockWareDTO.getSkuId());
            newGoodsSkuStockWareDTO.setSkuCode(goodsSkuStockWareDTO.getSkuCode());
            newGoodsSkuStockWareDTO.setWeight(goodsSkuStockWareDTO.getWeight());
            newGoodsSkuStockWareDTO.setGoodsName(goodsSkuStockWareDTO.getGoodsName());
            if (goodsSkuStockWareDTO != null) {
                newGoodsSkuStockWareDTO.setStockNum(dto.getSaleStockQuantity());
            } else {
                newGoodsSkuStockWareDTO.setStockNum(0);
            }
            goodsSkuStockWareDTOS.add(newGoodsSkuStockWareDTO);
        });
        return goodsSkuStockWareDTOS;
    }

    /***
     * 分仓的库存信息更新
     * @param warehouseStocks sku分仓添加库存集合
     * @param wareAndGoodsSkus sku分仓库存集合
     * @param now 时间
     * @param msg 返回信息
     */
    private void pre2RealWare(List<GoodsWarehouseStockDO> warehouseStocks, WareAndSkuIdsDTO wareAndGoodsSkus, LocalDateTime now, AtomicReference<String> msg) {
        wareAndGoodsSkus.getWareAndGoodsSkus().stream().anyMatch(dto -> {
            GoodsWarehouseStockDO warehouseStockDO = warehouseStocks.stream().filter(w ->
                    w.getWarehouseId().equals(dto.getWareId()) && w.getGoodsSkuId().equals(dto.getSkuId())
            ).findAny().orElse(null);
            if (warehouseStockDO != null) {
                //如果转真实的库存大于仓库实际库存 不能转
                if (dto.getStockNum() > warehouseStockDO.getSaleStockQuantity()) {
                    msg.set("sku编码:" + dto.getSkuCode() + "转真实的库存数不能大于实际库存数");
                    return true;
                }
                //先转分仓中的预售
                warehouseStockDO.setUpdateTime(now);
                warehouseStockDO.setSaleStockQuantity(warehouseStockDO.getSaleStockQuantity() + dto.getStockNum());
                warehouseStockMapper.updateById(warehouseStockDO);
            }
            return false;
        });
    }

    /**
     * sku总库存更新
     *
     * @param stockMap    sku添加库存集合
     * @param goodsStocks sku库存集合
     * @param now         时间
     * @param msg         返回信息
     */
    private void pre2RealStock(Map<Long, Integer> stockMap, List<GoodsStockDO> goodsStocks, LocalDateTime now, AtomicReference<String> msg) {
        stockMap.forEach((k, v) -> {
            GoodsStockDO goodsStock = goodsStocks.stream().filter(g -> g.getGoodsSkuId().equals(k)).findAny().orElse(null);
            if (goodsStock != null) {
                goodsStock.setUpdateTime(now);
                //总库存+
                goodsStock.setGoodsSkuStorage(goodsStock.getGoodsSkuStorage() + v);
                //预售库存-
                if (goodsStock.getGoodsSkuStorage() > 0 && goodsStock.getGoodsSkuStorage() > v) {
                    msg.set("sku编码:" + goodsStock.getGoodsSkuCode() + "转真实的库存数不能大于实际库存数");
                }
                goodsStock.setPreStorage(goodsStock.getGoodsSkuStorage() - v);
                if (StringUtils.isNotEmpty(msg.get())) {
                    goodsStockMapper.updateById(goodsStock);
                }
            }
        });
    }

    /**
     * 供应链清除库存
     *
     * @param dto
     */
    private List<GoodsWarehouseStockDO> clearSupplyMaterial(ClearSkuMaterialDTO dto,  List<GoodsWarehouseStockDO> warehouseStocks) {
        logger.info("清除的库存信息参数:{}", JSONObject.toJSONString(dto));
        logger.info("获取仓库的库存信息:{}", JSONObject.toJSONString(warehouseStocks));
        if (CollectionUtil.isNotEmpty(warehouseStocks)) {
            //物料对应关系
            List<GoodsMaterialRelationDTO> relations = dto.getRelations();
            List<CommodityStockReleaseDTO> stockRelease = new ArrayList<>(warehouseStocks.size());
            relations.stream().forEach(re -> {
                GoodsWarehouseStockDO warehouseStockDO = warehouseStocks.stream().filter(w -> w.getGoodsSkuId().equals(re.getSkuId())).findAny().orElse(null);
                if (warehouseStockDO != null) {
                    CommodityStockReleaseDTO commodityStockReleaseDTO = new CommodityStockReleaseDTO();
                    commodityStockReleaseDTO.setMaterialId(re.getMaterialId());
                    commodityStockReleaseDTO.setWarehouseId(warehouseStockDO.getWarehouseId());
                    //库存数量的计算为 sku下的仓库中的库存数*商品物料对应关系的数量(系数)
                    commodityStockReleaseDTO.setStockNum(warehouseStockDO.getSaleStockQuantity() * re.getCompNum());
                    stockRelease.add(commodityStockReleaseDTO);
                }
            });
            if (CollectionUtil.isNotEmpty(stockRelease)) {
                logger.info("调用供应链的库存信息:{}", JSONObject.toJSONString(stockRelease));
                supplySkuStockService.commodityStockRelease(stockRelease, dto.getUserName());
            }
        }

        return warehouseStocks;
    }

    /**
     * 清除库存同步redis
     * @param dto
     * @param warehouseStockes 分仓信息
     */
    private void clearSupplyStockRedis(ClearSkuMaterialDTO dto, List<GoodsWarehouseStockDO> warehouseStockes ){

    }
}
